package com.gandong8.trace.tool.config.rocketmq;

import com.gandong8.trace.tool.config.GlobalProperties;
import com.gandong8.trace.tool.config.rocketmq.properties.RocketMqProducerProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
@EnableConfigurationProperties({RocketMqProducerProperties.class, GlobalProperties.class})
@Slf4j
public class RocketMqProducerConf {

    @Autowired
    private RocketMqProducerProperties producerProperties;
    @Autowired
    private GlobalProperties globalProperties;

    @Bean(name="rocketMqProducer", destroyMethod = "shutdown")
    public DefaultMQProducer createProducer() throws MQClientException {
        if(!globalProperties.getRocketMqProducerOpen()) {
            System.err.println("rocketMq producer not allowed");
            return null;
        }
        DefaultMQProducer producer = new DefaultMQProducer(producerProperties.getGroupName());
        producer.setNamesrvAddr(producerProperties.getNamesrvAddr());
        producer.setVipChannelEnabled(false);
        producer.setMaxMessageSize(producerProperties.getMaxMessageSize());
        producer.setSendMsgTimeout(producerProperties.getSendMsgTimeOut());
        producer.setRetryTimesWhenSendAsyncFailed(producerProperties.getRetryTimesWhenSendFailed());
        producer.start();
        log.info("----rocketmq producer server start!----");
        return producer;
    }

    /**
     * RocketMQLog:WARN No appenders could be found for logger (io.netty.util.internal.InternalThreadLocalMap).
     * RocketMQLog:WARN Please initialize the logger system properly.
     *
     * if dubbo
     * log4j:WARN No appenders could be found for logger (org.apache.dubbo.common.logger.LoggerFactory).
     * log4j:WARN Please initialize the log4j system properly.
     *  System.setProperty("dubbo.application.logger", "slf4j");
     */
    @PostConstruct
    public void initLog() {
        //System.setProperty(ClientLogger.CLIENT_LOG_USESLF4J, "true");
        //System.setProperty(ClientLogger.CLIENT_LOG_LEVEL, "ERROR");
    }
}
